package controller

import (
	"github.com/gin-gonic/gin"
	"go-web/service"
	"net/http"
)

type ShortenInput struct {
	URL string `json:"url" binding:"required"`
}

func Shorten(c *gin.Context) {
	var input ShortenInput
	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
		return
	}

	link, err := service.CreateShortLink(input.URL)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "生成短链接失败"})
		return
	}

	host := c.Request.Host
	shortURL := "http://" + host + "/" + link.ShortLink

	c.JSON(http.StatusOK, gin.H{
		"short_url":  shortURL,
		"short_id":   link.ShortLink,
		"original":   link.OriginalURL,
		"created_at": link.CreatedAt,
	})

}

func Redirect(c *gin.Context) {
	shortID := c.Param("short_id")

	link, err := service.ResolveShortLink(shortID)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "短链接不存在"})
		return
	}

	c.Redirect(http.StatusFound, link.OriginalURL) // 302 重定向
}
